﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebDomain.Abstract;
using WebDomain.Concrete;
using CZTopComputers.Models;
using WebDomain.Entities;

namespace CZTopComputers.Controllers
{
    public class ProductController : Controller
    {
        public int PageSize = 4;
        private IProductRepository repo;

        public ProductController()
        {
            repo = new EFProductRepository();
        }
        public ActionResult Product(int product)
        {
            return View(repo.Products.FirstOrDefault(p=>p.ID==product));
        }
        public ActionResult Index(string category, int page=1)
        {
            ProductsListViewModel viewModel = new ProductsListViewModel
            {
                Products = repo.Products
                .Where(p => category==null|| p.Type==category)
                .OrderBy(p => p.ID)
                .Skip((page-1)*PageSize)
                .Take(PageSize),
                PagingInfo = new PagingInfo {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = repo.Products.Where(p => category == null || p.Type == category).Count()
                },
                Categories=repo.Products
                .Select(x=>x.Type)
                .OrderBy(x=>x)
                .Distinct(),
                CurrentCategory = category
            };
            return View(viewModel);
        }
        public FileResult GetImage(int ID)
        {
            Product prod = repo.Products.FirstOrDefault(p => p.ID == ID);
            if (!(prod == null || prod.ImageData==null))
            {
                return File(prod.ImageData, prod.ImageMimeType);
            }
            return null;
        }
    }
}
